package com.wgj.android.zfp;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.wgj.android.http.weixin.event.CleanEvent;
import com.wgj.android.http.weixin.WXFormatUtil;
import com.wgj.android.http.weixin.WXHttp;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.model.BaseRequest;
import com.wgj.android.http.weixin.model.CleanInfo;
import com.wgj.android.http.weixin.model.GetMsgBody;
import com.wgj.android.http.weixin.model.Msg;
import com.wgj.android.http.weixin.model.SendMsgBody;
import com.wgj.android.utils.CacheUtils;

import org.greenrobot.eventbus.EventBus;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/11/28.
 */

public class CleanFirendsTask implements  Runnable {
    private static String TAG="CleanFirendsTask";
    private Gson gson = new Gson();
    private String toUserName;
    private String headImgUrl;
    private String toNickName;
    private GetMsgBody getMsgBody;
    private BaseRequest baseRequest;
    private SendMsgBody sendMsg;


    public CleanFirendsTask(String toUserName,String toNickName,String headImgUrl) {
        this.toNickName=toNickName;
        this.headImgUrl=headImgUrl;
        this.toUserName=toUserName;
    }

    @Override
    public void run() {
        if (toUserName.startsWith("@@"))return;//微信群不需要
        baseRequest = new BaseRequest();
        baseRequest.setDeviceID("e" + (WXFormatUtil.getRand15Num()));
        baseRequest.setSid(WeiXinCacheUtil.getInfo().getWxsid());
        baseRequest.setSkey(WeiXinCacheUtil.getInfo().getSkey());
        baseRequest.setUin(Long.parseLong(WeiXinCacheUtil.getInfo().getWxuin()));

        Msg msg = new Msg();
        String rid = WXFormatUtil.getRandIDNum();
        msg.setClientMsgId(rid);
        msg.setLocalID(rid);
        msg.setFromUserName(WeiXinCacheUtil.getInfo().getUserName());
        msg.setToUserName(toUserName);
        //msg.setContent("/:share您好,我是"+CacheUtils.getMember().getM_nick()+",非常荣幸好友有你!\"旺旺i管家\" 正在帮我问候像您一样一直关爱我的人,\"旺旺i管家\" 智能生活服务APP, 自动检测, 自动分享, 安全方便, 立刻点击下载体验: "+ CacheUtils.getMember().getShareUrl());
        msg.setContent("111");
        sendMsg = new SendMsgBody();
        sendMsg.setBaseRequest(baseRequest);
        sendMsg.setMsg(msg);
        getMsgBody = new GetMsgBody();
        getMsgBody.setSyncKey(WeiXinCacheUtil.getSynckey());
        getMsgBody.setBaseRequest(baseRequest);
        getMsgBody.setRr(WXFormatUtil.getNDate());
        String url = "http://" + WeiXinCacheUtil.getInfo().getBaseUrl() + "/cgi-bin/mmwebwx-bin/webwxsendmsg";

        try {
            //post正在发送消息的微信好友
            EventBus.getDefault().post(new CleanEvent(toNickName, CleanEvent.type.CHECKING));

            baseRequest.setDeviceID("e" + (WXFormatUtil.getRand15Num()));
            WXHttp.obtain().post(url, gson.toJson(sendMsg), new WXHttp.WXHttpCallback() {
                @Override
                public void onSuccess(String body) {
                    Log.i(TAG, "发送到:".concat(toNickName).concat("  ").concat(new SimpleDateFormat("HH:mm:ss").format(new Date())));//todo delete
                    if (!body.contains("1101") || !body.contains("1102") || !body.contains("1205")) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        CleanInfo cleanInfo=WeiXinCacheUtil.getCleanInfo(WeiXinCacheUtil.getInfo().getWxuin());
                        cleanInfo.getNickNames().add(toNickName);
                        WeiXinCacheUtil.saveCleanInfo(WeiXinCacheUtil.getInfo().getWxuin(),cleanInfo);
                        checkMsg();
                    }else {

                    }
                }

                @Override
                public void onFailed(boolean isNettWork) {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void checkMsg() {
        String url = "http://" + WeiXinCacheUtil.getInfo().getBaseUrl() + "/cgi-bin/mmwebwx-bin/webwxsync?" +
                "sid=".concat(WeiXinCacheUtil.getInfo().getWxsid()) +
                "&skey=".concat(WeiXinCacheUtil.getInfo().getSkey());
        try {
            WXHttp.obtain().post(url, gson.toJson(getMsgBody), new WXHttp.WXHttpCallback() {
                @Override
                public void onSuccess(String body) {
                    JSONObject jsonObject= JSONObject.parseObject(body);
                    JSONArray jsonArray = jsonObject.getJSONArray("AddMsgList");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject ob= (JSONObject) jsonArray.get(i);
                        Log.e(TAG,ob.getString("FromUserName")+"USER_NAME:"+toUserName);
                        if(ob.getString("FromUserName").equals(toUserName)){

                        }
                        if(ob.getString("FromUserName").equals(toUserName) && ob.getString("Status").equals("4")){
                            EventBus.getDefault().postSticky(new CleanEvent(toNickName,CleanEvent.type.CLEAN));
                            ModifyTask modifyTask = new ModifyTask(toUserName, toNickName, baseRequest);
                            CleanFirendsTaskManager.getInstance().addModifyTask(modifyTask);
                            break;
                        }
                    }
                }

                @Override
                public void onFailed(boolean isNettWork) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getToUserName() {
        return toUserName;
    }

    public void setToUserName(String toUserName) {
        this.toUserName = toUserName;
    }

    public String getHeadImgUrl() {
        return headImgUrl;
    }

    public void setHeadImgUrl(String headImgUrl) {
        this.headImgUrl = headImgUrl;
    }

    public String getToNickName() {
        return toNickName;
    }

    public void setToNickName(String toNickName) {
        this.toNickName = toNickName;
    }
}
